﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Aribaccio
{
    /// <summary>
    /// 定义扩展设备校验
    /// </summary>
    public static class ExtendDeviceCheck
    {
        /// <summary>
        /// 计算校验和[去除头信息]
        /// </summary>
        /// <param name="argDataItem">原字节数组</param>
        /// <returns>校验和字节</returns>
        public static byte ToCheckSum(this byte[] argDataItem)
        {
            byte sum = 0;
            if (argDataItem != null && argDataItem.Count() > 0)
            {
                int iSum = 0;
                //计算效验和（去除头信息）
                for (int i = 1; i < argDataItem.Length; i++)
                {
                    iSum += argDataItem[i];
                }
                sum = (byte)(iSum & 0x00ff);
            }
            return sum;
        }

        /// <summary>
        /// 计算CRC[后两位字节]
        /// </summary>
        /// <param name="argDataItem">原字节数组</param>
        /// <returns>CRC两位字节数组</returns>
        public static byte[] ToCheckCRCModbus(this byte[] argDataItem)
        {
            //生成的两位校验码
            byte[] redata = new byte[2];
            if (argDataItem == null || argDataItem.Count() <= 0) return redata;
            try
            {
                //计算并填写CRC校验码
                int crc = 0xffff;
                int len = argDataItem.Length;
                for (int n = 0; n < len; n++)
                {
                    byte i;
                    crc = crc ^ argDataItem[n];
                    for (i = 0; i < 8; i++)
                    {
                        int TT;
                        TT = crc & 1;
                        crc = crc >> 1;
                        crc = crc & 0x7fff;
                        if (TT == 1)
                        {
                            crc = crc ^ 0xa001;
                        }
                        crc = crc & 0xffff;
                    }
                }
                //赋值
                redata[0] = (byte)((crc & 0xff));
                redata[1] = (byte)((crc >> 8) & 0xff);
            }
            catch (Exception) { }
            return redata;
        }
    }
}
